import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function Square(props) {
  return (
    <button
      className="square"
      style={{ color: props.highlight ? "green" : "" }}
      onClick={() => props.onClick()}
    >
      {props.value}
    </button>
  )
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        key={i}
        value={this.props.squares[i]}
        highlight={this.props.winLine.includes(i)}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  renderBoard() {
    const board = [];
    for (let row = 0; row < 3; row++) {
      const boardRow = []
      for (let col = 0; col < 3; col++) {
        boardRow.push(this.renderSquare(row * 3 + col))
      }
      board.push(<div className="board-row" key={row}>{boardRow}</div>)
    }
    return board
  }

  render() {
    return (
      <div>
        {this.renderBoard()}
      </div >
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null)
      }],
      xIsNext: true,
      stepNumber: 0,
      isReverse: false,
      sideLenght: '100px'
    }
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares,
        coord: [Math.floor(i / 3), i % 3]
      }]),
      xIsNext: !this.state.xIsNext,
      stepNumber: this.state.stepNumber + 1
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0
    })
  }

  movesReverse() {
    this.setState({
      isReverse: !this.state.isReverse
    })
  }

  restart() {
    this.setState({
      history: [{
        squares: Array(9).fill(null)
      }],
      xIsNext: true,
      stepNumber: 0,
    })
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    let status = winner ?
      <b style={{ color: "green" }}>胜利者: {winner.winner}</b> :
      `下一个玩家: ${this.state.xIsNext ? 'X' : 'O'}`;
    if (this.state.stepNumber === 9 && !winner) {
      status = <b style={{ color: "#49460c" }}>平局</b>
    }
    const winLine = winner ? winner.line : [];
    const moves = history.map((item, step) => {
      const desc = step ?
        `跳转到 #${step} - 最近一步坐标(${item.coord[0]},${item.coord[1]})` :
        `跳转到游戏开始`;
      return (
        <li key={step} className="mb5">
          <button
            onClick={() => this.jumpTo(step)}
            dangerouslySetInnerHTML={{
              __html: step === this.state.stepNumber ? desc.bold() : desc
            }}
          />
        </li>
      )
    })
    this.state.isReverse && moves.reverse();
    const styleObj = {
      '--side-lenght': `${parseFloat(this.state.sideLenght)}px`
    }

    return (
      <div className="game" style={styleObj}>
        <div className="game-board">
          <Board
            squares={current.squares}
            winLine={winLine}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div className="game-status">
            <div>游戏状态：{status}</div>
            <button onClick={() => this.restart()}>重新开始</button>
          </div>
          <button onClick={() => this.movesReverse()}>
            历史记录{this.state.isReverse ? '升序' : '倒序'}
          </button>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return {
        winner: squares[a],
        line: lines[i]
      };
    }
  }
  return null;
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);
